/*
 License
 
 Copyright © 2012 Kevin Kimmich
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights to 
 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 the Software, and to permit persons to whom the Software is furnished to do so, 
 subject to the following conditions:
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
 FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "crcore.h"
#include "messaging.h"
#include "stream.h"
#include "kuato_http.h"
#include "kuato_http_operations.h"
#include "regex.h"
#include <signal.h>
#include <ctype.h>

const char CRLF[] = {13,10,0};
const char CRLFCRLF[] = {13,10,13,10,0};

const result_code HTTP_CONTINUE = {100,"Continue"};
const result_code HTTP_SWITCHING_PROTOCOLS = {101,"Switching Protocols"};
const result_code HTTP_OK = {200,"OK"};
const result_code HTTP_CREATED = {201,"Created"};
const result_code HTTP_ACCEPTED = {202,"Accepted"};
const result_code HTTP_BAD_REQUEST = {400,"Bad Request"};
const result_code HTTP_UNAUTHORIZED = {401,"Unauthorized"};
const result_code HTTP_NOT_FOUND = {404,"Not Found"};
const result_code HTTP_METHOD_NOT_ALLOWED = {405,"Method Not Allowed"};
const result_code HTTP_INTERNAL_SERVER_ERROR = {500,"Internal Server Error"};

/*
		"100"  ; Section 10.1.1: Continue
		| "101"  ; Section 10.1.2: Switching Protocols
		| "200"  ; Section 10.2.1: OK
		| "201"  ; Section 10.2.2: Created
		| "202"  ; Section 10.2.3: Accepted
		| "203"  ; Section 10.2.4: Non-Authoritative Information
		| "204"  ; Section 10.2.5: No Content
		| "205"  ; Section 10.2.6: Reset Content
		| "206"  ; Section 10.2.7: Partial Content
		| "300"  ; Section 10.3.1: Multiple Choices
		| "301"  ; Section 10.3.2: Moved Permanently
		| "302"  ; Section 10.3.3: Found
		| "303"  ; Section 10.3.4: See Other
		| "304"  ; Section 10.3.5: Not Modified
		| "305"  ; Section 10.3.6: Use Proxy
		| "307"  ; Section 10.3.8: Temporary Redirect
		| "400"  ; Section 10.4.1: Bad Request
		| "401"  ; Section 10.4.2: Unauthorized
		| "402"  ; Section 10.4.3: Payment Required
		| "403"  ; Section 10.4.4: Forbidden
		| "404"  ; Section 10.4.5: Not Found
		| "405"  ; Section 10.4.6: Method Not Allowed
		| "406"  ; Section 10.4.7: Not Acceptable

		| "407"  ; Section 10.4.8: Proxy Authentication Required
		| "408"  ; Section 10.4.9: Request Time-out
		| "409"  ; Section 10.4.10: Conflict
		| "410"  ; Section 10.4.11: Gone
		| "411"  ; Section 10.4.12: Length Required
		| "412"  ; Section 10.4.13: Precondition Failed
		| "413"  ; Section 10.4.14: Request Entity Too Large
		| "414"  ; Section 10.4.15: Request-URI Too Large
		| "415"  ; Section 10.4.16: Unsupported Media Type
		| "416"  ; Section 10.4.17: Requested range not satisfiable
		| "417"  ; Section 10.4.18: Expectation Failed
		| "500"  ; Section 10.5.1: Internal Server Error
		| "501"  ; Section 10.5.2: Not Implemented
		| "502"  ; Section 10.5.3: Bad Gateway
		| "503"  ; Section 10.5.4: Service Unavailable
		| "504"  ; Section 10.5.5: Gateway Time-out
		| "505"  ; Section 10.5.6: HTTP Version not supported
		| extension-code
*/

void remove_white_space( char* str )
{
	//remove leading white space
	int len = strlen(str);
	char* lws = str;
	while(lws[0] && (lws[0]==' ' || lws[0]=='\t'))
	{
		lws[0]=0;
		lws++;
		len--;
	}
	if(len)
	{
		//remove trailing white space
		char* tws=lws+len-1;
		while((tws != lws) && (tws[0]==' ' || tws[0]=='\t'))
		{
			tws[0]=0;
			tws--;
			len--;
		}
		memmove(str,lws,len);
		*(str+len)=0;
	}
}


static void parse_request_line(int line_count,request* req,char* pos)
{
	stringbuffer* line = NULL;
	
	if(line_count==0)
	{
		remove_white_space(pos);
		char* tmp;
		for(tmp = strstr(pos," ");tmp;pos=tmp+1,tmp=strstr(pos," "))
		{
			*tmp=0;
			if(req->method==NULL)
				req->method=pos;
			else
			{
				if(req->url==NULL)
					req->url=pos;
			}
		}
		req->version=pos;
	}
	else
	{
		if(*pos==' ' || *pos=='\t')
		{
			remove_white_space(pos);
			sb_add_data(line,pos);
		}
		else
		{
			line = sb_create();
			char* value = strstr(pos,":");
			if(value)
			{
				*value=0;
				value++;
				remove_white_space(pos);
				remove_white_space(value);
				sb_add_data(line,value);
				for(value=pos;*value;value++)
					*value=toupper(*value);
				
				hash_string_insert(&req->dict,pos,line);
			}
			else
			{
				sb_destroy(line);
				THROW(HTTP_HEADER_ERROR,"Header line does not have a ':'");
			}
		}
	}
}

void parse_request_header(connection_context* ctx, method* m)
{
	char* ln, *pos;
	int line_count = 0;
	request* req = &m->req;
	
	for(pos=req->header,ln=strstr(pos,CRLF);ln;pos=ln+2,ln=strstr(pos,CRLF))
	{
		*ln=0;
		*(ln+1)=0;
	
		parse_request_line(line_count,req,pos);
		line_count++;
	}
	
	if(pos)
	{
		parse_request_line(line_count,req,pos);
		line_count++;
	}
	
	if(!(req->method && req->url && req->version))
				THROW(HTTP_HEADER_ERROR,"Request missing method, uri, or version");
	
	parse_url(req->url,&req->uri);
	
	req->mtype=INVALID;
	m->status = METHOD_HEADER_ERROR;
	
	if(strcmp(req->method,"GET")==0)
	{
		req->mtype=GET;
		m->status = METHOD_REQUEST_COMPLETE;
		return;
	}

	if(strcmp(req->method,"POST")==0)
	{
		req->mtype=POST;
		stringbuffer* value = hash_string_lookup(&req->dict,"CONTENT-LENGTH");
		if(value==NULL)
			THROW(HTTP_HEADER_ERROR,"Missing content-length field")
		else
		{
			m->status = METHOD_WAIT_BODY;
			req->content_length = strtoul(sb_get_buffer(value),NULL,0);
			return;
		}
	}

	if(strcmp(req->method,"HEAD")==0)
	{
		req->mtype=HEAD;
		m->status = METHOD_REQUEST_COMPLETE;
		return;
	}
	
	if(strcmp(req->method,"PUT")==0)
	{
		req->mtype=PUT;
		m->status = METHOD_REQUEST_COMPLETE;
		return;
	}
	
	if(strcmp(req->method,"DELETE")==0)
	{
		req->mtype=DELETE;
		m->status = METHOD_REQUEST_COMPLETE;
		return;
	}
	
	if(strcmp(req->method,"CONNECT")==0)
	{
		req->mtype=CONNECT;
		m->status = METHOD_REQUEST_COMPLETE;
		return;
	}
	
	if(strcmp(req->method,"TRACE")==0)
	{
		req->mtype=TRACE;
		m->status = METHOD_REQUEST_COMPLETE;
		return;
	}
	
	if(strcmp(req->method,"OPTIONS")==0)
	{
		req->mtype=OPTIONS;
		m->status = METHOD_REQUEST_COMPLETE;
		return;
	}
	
	if(strcmp(req->method,"PATCH")==0)
	{
		req->mtype=PATCH;
		m->status = METHOD_REQUEST_COMPLETE;
		return;
	}

	THROW(HTTP_HEADER_ERROR,"Method %s not supported",req->method);	

}

static void parse_response_line(int line_count,response* resp,char* pos,char* header)
{
	stringbuffer* line = NULL;
	
	if(line_count==0)
	{
		remove_white_space(pos);
		char* tmp;
		for(tmp = strstr(pos," ");tmp;pos=tmp+1,tmp=strstr(pos," "))
		{
			*tmp=0;
			if(resp->version==NULL)
				resp->version=pos;
			else
			{
				if(resp->status_code==NULL)
					resp->status_code=pos;
			}
		}
		resp->reason_phrase=pos;
	}
	else
	{
		if(*pos==' ' || *pos=='\t')
		{
			remove_white_space(pos);
			sb_add_data(line,pos);
		}
		else
		{
			line = sb_create();
			char* value = strstr(pos,":");
			if(value)
			{
				*value=0;
				value++;
				remove_white_space(pos);
				remove_white_space(value);
				sb_add_data(line,value);
				for(value=pos;*value;value++)
					*value=toupper(*value);
					
				hash_string_insert(&resp->dict,pos,line);
			}
			else
			{
				sb_destroy(line);
				free(header);
				THROW(HTTP_HEADER_ERROR,"Response header field missing ':'");
			}
		}
	}
}

void parse_response_header(connection_context* ctx, method* m)
{
	char* ln, *pos;
	int line_count = 0;
	response* resp = &m->resp;
	char* header = strdup(resp->header);
	
	for(pos=header,ln=strstr(pos,CRLF);ln;pos=ln+2,ln=strstr(pos,CRLF))
	{
		*ln=0;
		*(ln+1)=0;
		
		parse_response_line(line_count,resp,pos,header);
		
		line_count++;
	}
	
	if(pos)
		parse_response_line(line_count,resp,pos,header);
	
	if(!(resp->version && resp->status_code && resp->reason_phrase))
	{
		free(header);
		THROW(HTTP_HEADER_ERROR,"Response header missing version, status code, or reason phrase");
	}
	
	resp->content_length = 0;
	
	stringbuffer* value = hash_string_lookup(&resp->dict,"TRANSFER-ENCODING");
	
	value = hash_string_lookup(&resp->dict,"CONTENT-LENGTH");
	if(value)
		resp->content_length = strtoul(sb_get_buffer(value),NULL,0);

	m->status = METHOD_WAIT_BODY;
	
	free(header);
}

/*

The following line is the regular expression for breaking-down a URI
   reference into its components.

      ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
       12            3  4          5       6  7        8 9

http://www.ics.uci.edu/pub/ietf/uri/#Related

   results in the following subexpression matches:

      $1 = http:
      $2 = http
      $3 = //www.ics.uci.edu
      $4 = www.ics.uci.edu
      $5 = /pub/ietf/uri/
      $6 = <undefined>
      $7 = <undefined>
      $8 = #Related
      $9 = Related

   where <undefined> indicates that the component is not present, as is
   the case for the query component in the above example.  Therefore, we
   can determine the value of the four components and fragment as

      scheme    = $2
      authority = $4
      path      = $5
      query     = $7
      fragment  = $9
*/

void cleanup_uri(URI* uri)
{
	if(uri->scheme)
		free(uri->scheme);
	if(uri->authority)
		free(uri->authority);
	if(uri->path)
		free(uri->path);
	if(uri->query)
		free(uri->query);
	if(uri->fragment)
		free(uri->fragment);
}

int parse_url(const char* url, URI* uri)
{
	memset(uri,0,sizeof(URI));
	regex_t r;
	int err = regcomp(&r,"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?",REG_EXTENDED);
	if(err)
	{
		regfree(&r);
		return -1;
	}
	
	regmatch_t matches[10];
	regexec(&r,url,10,matches,0);
	const int indices[] = {2,4,5,7,9};
	
	int i;
	char** uri_element = (char**)uri;
	for(i=0;i<5;i++)
	{
		if(matches[indices[i]].rm_so >= 0)
		{
			int len = matches[indices[i]].rm_eo-matches[indices[i]].rm_so;
			uri_element[i] = malloc(len+1);
			uri_element[i][len]=0;
			memcpy(uri_element[i],url+matches[indices[i]].rm_so,len);
		}
	}
	regfree(&r);
	return 0;
}


char* unescape_url(const char* url)
{
	if(url==NULL)
		return NULL;	
	int len = strlen(url);
	char* str = (char*)malloc(len+1);
	const char* p = url;
	char* p2 = str;

	while(*p && ((p2-str) < len))
	{
		unsigned char c;
		if(*p=='%')
		{
			p++;
			if(*p>='a' && *p<='f')
				c=(*p-'a'+10) << 4;
			else
			{
				if(*p>='A' && *p<='F')
					c=(*p-'A'+10) << 4;
				else
				{
					if(*p>='0' && *p<='9')
						c=(*p-'0') << 4;
					else 
						goto fail;
				}
			}
			p++;
			if(*p>='a' && *p<='f')
				c+=(*p-'a'+10);
			else
			{
				if(*p>='A' && *p<='F')
					c+=(*p-'A'+10);
				else
				{
					if(*p>='0' && *p<='9')
						c+=(*p-'0');
					else
						goto fail;
				}
			}
			p++;
		}
		else
		{
			c=*p;
			p++;
		}
		
		*p2=c;
		p2++;
	}
	*p2=0;
	return str;
	
fail:
	free(str);
	return NULL;
	
}
